package pe.gob.sunat.proyecto.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import pe.gob.sunat.proyecto.exception.LoginException;
import pe.gob.sunat.proyecto.model.Usuario;
import pe.gob.sunat.proyecto.service.UsuarioService;

@Controller
public class LoginController {
	private static final Logger logger = Logger
			.getLogger(LoginController.class);

	@Autowired
	private UsuarioService usuarioService;

	@RequestMapping("/bienvenida.htm")
	public String bienvenida(){
		Authentication authentication = 
			SecurityContextHolder.getContext().getAuthentication();
		logger.debug(authentication.getName());
		return "bienvenida";
	}
	
	
	@RequestMapping("/login.htm")
	public ModelAndView login(@RequestParam("username") String username,
			@RequestParam("password") String password) throws Exception {
		logger.debug("Inicio handleRequest");
		try {
			Usuario usuario = usuarioService.login(username, password);
			return new ModelAndView("bienvenida", "usuario", usuario);
		} catch (LoginException le) {
			return new ModelAndView("forward:index.jsp", "mensaje", le.getMessage());
		}
	}
}
